<?php

class Login_Page_Main_Exception extends Page_Main_Exception {}
class Login_Page_Main_Invalid_Exception extends Login_Page_Main_Exception {}

class Login_Page_Main extends Page_Main {

	protected function URL($array = array()){
		return parent::URL(array_merge(
			array('login'),
			$array
		));
	}

	public function rid($array = array()){
		return array_merge(
			array('login'),
			$array
		);
	}

	protected function __construct($args){
		parent::__construct($args);
		$language = Authentication::getInstance()->user()->language();

		$this->title = $language->translate(array('login','title'));

		$this->form = new Form(array("login"), $this->URL());

		$username = Form_Field::Create('username','text');
		$username->title($language->translate(array('login','username')));
		$username->validate('not_empty');
		$this->form->add($username);

		$password = Form_Field::Create('password','password');
		$password->title($language->translate(array('login','password')));
		$password->validate('not_empty');
		$this->form->add($password);

		$submit = Form_Field::Create('submit','submit');
		$submit->title($language->translate(array('login','submit')));

		$this->form->add($submit);
	}

	public function Output(){
		$parent = parent::output();
		$parent->module = Output::getInstance()->Template(array('login','page'));
		$parent->module->form = $this->form->output();
		$parent->module->title = $this->title;
		return $parent;
	}

	public static function Load($args){
		if(Authentication::getInstance()->user() instanceof User_Guest){
			return new Login_Page_Main($args);
		}
		throw new Login_Page_Main_Invalid_Exception($data);
	}

	public function run(){

		$this->form->run();

		try {
			$data = $this->form->data();
			$user = Authentication::getInstance()->authenticate(array('username' => $data['username'], 'password' => $data['password']));
			CMS::Redirect(parent::URL(explode('/',$user->home())));
		} catch(Exception $e){
		}
	}



}
